package com.xingyun.kingdee.erp.tools.common;

import java.beans.Introspector;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

/**
 * @author lingo
 * @version v1.0
 * @date 2020/4/29 17:33
 * @Company www.xyb2b.com
 */

public class Reflection {

    private static final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");
    private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");


    public static <A, B> String getMethodToFieldName(XyFunction<A, B> fn) {
        try {
            SerializedLambda serializedLambda = getSerializedLambda(fn);
            String getter = serializedLambda.getImplMethodName();
            if (GET_PATTERN.matcher(getter).matches()) {
                getter = getter.substring("get".length());
            } else if (IS_PATTERN.matcher(getter).matches()) {
                getter = getter.substring("is".length());
            }else{
                throw new RuntimeException(getter + "不是getter方法");
            }
            return Introspector.decapitalize(getter);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static SerializedLambda getSerializedLambda(XyFunction fn) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = fn.getClass().getDeclaredMethod("writeReplace");
        method.setAccessible(Boolean.TRUE);
        return (SerializedLambda) method.invoke(fn);
    }
}
